//
//  NetworkConnection.m
//  MusicOnline
//
//  Created by Le Thanh Hai on 6/6/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "NetworkConnection.h"
#import "CJSONSerializer.h"
#import "CJSONDeserializer.h"

@implementation NetworkConnection
@synthesize responseDic;

-(void)startConnection:(NSMutableDictionary*)requestDic 
{
    // requestHtmlBody = @"post_api=toi yeu em nhieu lam, adfb";
    NSMutableDictionary *tempRequestDic = [[NSMutableDictionary alloc] initWithDictionary: requestDic];
    NSLog(@"%@", [tempRequestDic description]);
    
    NSError **error = nil;
    CJSONSerializer *jsonSerializer = [CJSONSerializer serializer];
    NSData *bodyData = [jsonSerializer serializeDictionary:tempRequestDic error:error];
    // NSData *bodyData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];

    // Create the request.    
    
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.kurama.byethost24.com/API.php"]];   
    
    [theRequest setHTTPBody:bodyData];
    [theRequest setHTTPMethod: @"POST"];
    [theRequest setTimeoutInterval:60];
    [theRequest setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    
    if (!error) {        
        // create the connection with the request
        // and start loading the data
        NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
        if (theConnection) {
            // Create the NSMutableData to hold the received data.
            // receivedData is an instance variable declared elsewhere.
            receivedData = [[NSMutableData data] retain];
        } else {
            // Inform the user that the connection failed.
        }
    } else {
        NSLog(@"Error: encode Dictionary to Json data");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.
    
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    
    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];
    
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    // NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    CJSONDeserializer *jsonDeserializer = [CJSONDeserializer deserializer];
    jsonDeserializer.options = kJSONDeserializationOptions_MutableContainers;
    NSError **error = nil;
    responseDic = [jsonDeserializer deserialize:receivedData error:error];
    // NSMutableDictionary *resDic = [jsonDeserializer deserializeAsDictionary:receivedData error:nil]; // WTF? why don't get NSMutableDictionary
    
    if (!error) {
        NSLog(@"decode json sucessful");
    } else {
        NSLog(@"Error: decode Json data to Dictionary");
    }
    
    // release the connection, and the data object
    [connection release];
    [receivedData release];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KEY_NOTIFICATION_NETWORK_FINISH object:self];
}

-(void)getAllListMusic
{
    NSMutableDictionary *requestDic = [[NSMutableDictionary alloc] init];
    [requestDic setObject:@"get_all_music" forKey:@"post_api"];
    [self startConnection:requestDic];
    [requestDic release];
    
    [appDelegate showBusyView:YES];
}

-(void)getAllDetailListMusic:(NSString*)week
{
    NSMutableDictionary *requesdDic = [[NSMutableDictionary alloc] init];
    [requesdDic setObject:@"get_all_detail" forKey:@"post_api"];
    [requesdDic setObject:week forKey:@"weekId"];
    [self startConnection:requesdDic];
    
    [requesdDic release];
    [appDelegate showBusyView:YES];
}
@end
